<template>
  <el-form-item
    :prop="props.prop"
    :rules="
      props.needValidate
        ? [{ validator: validate, trigger: 'change', required: true }]
        : []
    "
  >
    <el-cascader
      popper-class="cascader-hide-radio"
      ref="areaRef"
      v-model="area"
      :props="prop"
      placeholder="请选择所属区域"
      :disabled="disabled"
      :style="{ width: width }"
      :clearable="clearable"
      @change="changeSelect"
    />
  </el-form-item>
</template>

<script setup>
import { useUserStore } from '@/pinia/modules/user'
import { gerAreaByCode } from '@/api/api'
import areaCode from '@/components/area-cascader/areaCode.js'
import {
  watch,
  computed,
  ref,
  onMounted,
  getCurrentInstance,
  reactive,
  nextTick,
  toRaw
} from 'vue'
const emit = defineEmits([
  'update:modelValue',
  'areaChange',
  'update:areaString'
])
const props = defineProps({
  needValidate: {
    type: Boolean,
    default: true
  },
  prop: {
    type: String,
    default: ''
  },
  areaString: {
    type: String
  },
  clearable: {
    type: Boolean,
    default: false
  },
  modelValue: {
    type: Array,
    default(val) {
      return []
    }
  },
  width: {
    type: String,
    default: '500px'
  },
  maxLevel: {
    type: Number,
    default: 0
  },
  // 用来控制前面几层不能选择 0.省份disabled 1.市disabled 2....
  // 如果设置了disabledLevel 必须传正确的defaultArea进来
  disabledLevel: {
    type: [Number, String],
    default: 0
  },
  // 父子强制关联 true:可选任意一级  false:只能选中最后一级
  strictly: {
    type: Boolean,
    default: true
  },
  disabled: {
    type: Boolean,
    default: false
  },
  /*
   * search 搜索时候使用的 返回的最后一级地区code
   * registerAddress 选择户籍地址时使用
   * normalAddress  选择常住地址时使用
   */
  useType: {
    type: String,
    default: 'search'
  }
})
const areaRef = ref(null)
const area = ref(props.modelValue)
const calLeaf = (item, level) => {
  if (props.maxLevel) {
    if (item.isBelow) {
      return item.isBelow
    } else {
      return level >= props.maxLevel
    }
  } else {
    return item.isBelow
  }
}
const prop = reactive({
  lazy: true,
  label: 'name',
  checkStrictly: true,
  lazyLoad: async (node, resolve) => {
    const { data, level } = node
    if (data && data.children && data.children.length !== 0) {
      return resolve([])
    }
    if (level === 0) {
      // 获取全部省份
      const r = await getArea('000000')
      const targetData = []
      for (const item of r.data) {
        const temp = {
          id: item.id,
          name: item.name,
          value: item.id,
          disabled: calDiasbled(level),
          leaf: false
        }
        if (props.disabledLevel > -1) {
          // eslint-disable-next-line eqeqeq
          // item.id == props.defaultArea[level] && targetData.push(temp)
          // 只push广东省
          //  targetData.push(temp)
          item.id == areaCode.defaultProvince && targetData.push(temp)
        } else {
          targetData.push(temp)
        }
      }
      resolve(targetData)
    } else {
      // 根据省ID获取市
      const r = await getArea(data.id)
      const targetData = []
      for (const item of r.data) {
        const temp = {
          id: item.id,
          name: item.name,
          value: item.id,
          disabled: calDiasbled(level),
          // leaf: level >= props.maxLevel,
          leaf: calLeaf(item, level),
          loading: false
        }
        if (props.disabledLevel) {
          // 如果设置了不可选的level  node-level
          if (level > props.disabledLevel) {
            targetData.push(temp)
          } else {
            // eslint-disable-next-line eqeqeq
            item.id == props.modelValue[level] && targetData.push(temp)
          }
        } else {
          targetData.push(temp)
        }
      }
      resolve(targetData)
    }
  }
})
watch(
  () => props.modelValue,
  (newValue, oldValue) => {
    nextTick(() => {
      if (newValue.length == 0) {
        area.value = [areaCode.defaultProvince]
        emit('update:modelValue', area.value)
        emit('areaChange', area.value)
      } else {
        area.value = newValue
        emit('update:modelValue', newValue)
        emit('areaChange', newValue)
      }
      setTimeout(() => {
        if (areaRef.value) {
          emit(
            'update:areaString',
            areaRef.value.getCheckedNodes()[0]?.pathLabels.join('')
          )
        }
      }, 1000)
    })
  },
  { deep: true, immediate: true }
)
const valueChange = val => {}
const calDiasbled = nodeLevel => {
  if (!props.strictly) {
    return false
  }
  // 如果是有层级选择限制的 && nodeLevel< 层级限制的level
  if (props.disabledLevel > 0) {
    if (nodeLevel < props.disabledLevel) {
      return true
    } else {
      return false
    }
  } else {
    return false
  }
}

const changeSelect = val => {
  emit('update:modelValue', val)
  emit('areaChange', val)
  emit(
    'update:areaString',
    areaRef.value.getCheckedNodes()[0]?.pathLabels.join('')
  )
  areaRef.value.getCheckedNodes()[0].isLeaf &&
    areaRef.value.togglePopperVisible(false)
  console.log(areaRef.value.getCheckedNodes()[0])
}

const validate = (rule, value, callback) => {
  if (!value) {
    callback('请选择')
    return
  }
  if (!value[0]) {
    callback('请选择')
    return
  }
  console.log(areaRef.value)
  console.log(areaRef.value.getCheckedNodes()[0].isLeaf)
  if (areaRef.value.getCheckedNodes()[0].isLeaf) {
    return callback()
  } else {
    callback('请选择最后一级')
  }
}
const getArea = code => {
  return gerAreaByCode(code)
}
</script>
<style lang="scss" scoped></style>
